<?php declare(strict_types=1);

namespace App\Http\Business;

use App\Model\SystemMenu;
use App\Model\SystemUser;

/**
 * 公共-业务类
 * Class CommonBusiness
 * @package App\Business
 */
class CommonBusiness
{
        /**
         * 图片验证码
         * @return array
         */
        public static function captcha(): array
        {
                $intWidth = intval(get('width')) ?: 100;
                $intHeight = intval(get('height')) ?: 31;
                $strSessionId = session()->getSessionId();
                ob_start();
                getOperationCaptcha($intWidth, $intHeight, $strSessionId);
                $str_content = ob_get_contents();
                ob_end_clean();
                $strBase64 = base64_encode($str_content);
                $arrData = [
                        'key' => $strSessionId,
                        'captcha' => 'data:image/png;base64,' . $strBase64
                ];
                return callbackParam(0, true, $arrData);
        }

        /**
         * 获取路由
         * @return array
         */
        public static function routes(): array
        {
                $strUserId = request()->userId;
                $arrJoin = [];
                $arrGroupBy = [];
                if ($strUserId == 'lcl00000004-0819-e715-a6cf-dcf0210560ae') {
                        $arrWhere = ['system_menu.status' => 1];
                } else {
                        $arrWhere = [
                                'system_user_role.userId' => $strUserId,
                                'system_role.status' => 1,
                                'system_menu.status' => 1,
                                ['system_role_permissions.pseudoChecked', '<>', 3]
                        ];
                        $arrJoin['system_role_permissions'] = [
                                'table' => 'system_role_permissions',
                                'where' => ['system_role_permissions.menuId', '=', 'system_menu.menuId']
                        ];
                        $arrJoin['system_role'] = [
                                'table' => 'system_role',
                                'where' => ['system_role.roleId', '=', 'system_role_permissions.roleId']
                        ];
                        $arrJoin['system_user_role'] = [
                                'table' => 'system_user_role',
                                'where' => ['system_user_role.roleId', '=', 'system_role.roleId']
                        ];
                        $arrGroupBy = ['system_menu.menuId'];
                }
                $arrField = [
                        'system_menu.menuId',
                        'system_menu.pid',
                        'system_menu.name',
                        'system_menu.icon',
                        'system_menu.route',
                        'system_menu.path',
                        'system_menu.menuType',
                        'system_menu.urlParams',
                        'system_menu.pathParams',
                        'system_menu.powerDiscern'
                ];
                $arrOrderBy = ['system_menu.sort' => 'DESC'];
                $arrData = SystemMenu::getAll($arrWhere, $arrField, $arrOrderBy, $arrGroupBy, $arrJoin);
                $arrData = arrayGroupBy($arrData, 'menuType');
                $arrMenu = issetArrKey($arrData, 1, []);
                $arrMenuFormat = arrayValueToKey($arrMenu, 'menuId');
                $arrPermissions = issetArrKey($arrData, 2, []);
                $arrPermissionsFormat = arrayGroupBy($arrPermissions, 'pid');
                $arrPermissionsNew = [];
                foreach ($arrMenuFormat as $k => $v) {
                        $arrPermissionsNew[] = [
                                'id' => $v['powerDiscern'],
                                'operation' => array_column(issetArrKey($arrPermissionsFormat, $k, []), 'powerDiscern')
                        ];
                }
                $arrResult = [
                        'menu' => $arrMenu,
                        'permissions' => $arrPermissionsNew,
                ];
                return callbackParam(0, true, $arrResult);
        }

        /**
         * 个人设置
         * 获取个人信息展示
         * @return array
         */
        public static function personalSettingInfo(): array
        {
                $strUserId = request()->userId;
                $arrWhere = ['userId' => $strUserId];
                $arrField = ['realName', 'phone', 'avatar'];
                $arrResult = SystemUser::getOne($arrWhere, $arrField);
                $arrResult['avatar'] = getDomain() . $arrResult['avatar'];
                return callbackParam(0, true, $arrResult);
        }

        /**
         * 个人设置
         * 编辑个人信息
         * @return array
         */
        public static function personalSettingEdit(): array
        {
                $strUserId = request()->userId;
                $arrParam = post();
                $arrWhere = ['userId' => $strUserId];
                $arrField = ['realName', 'phone', 'avatar'];
                if (isset($arrParam['password']) && $arrParam['password']) {
                        if ($strUserId == 'lcl00000085-1cc4-59ef-08d2-65e11945e8b7') throw new \Exception('请不要修改演示账号密码');
                        $arrField[] = 'password';
                        $arrField[] = 'salt';
                }
                $arrOperationBefore = SystemUser::getOne($arrWhere, $arrField);
                if (!$arrOperationBefore) throw new \Exception('数据不存在');
                $strPhone = strAddslashes($arrParam['phone']);
                $strCheckPhone = SystemUser::getFieldValue(['phone' => $strPhone], 'userId');
                if ($strCheckPhone && $strCheckPhone != $strUserId) throw new \Exception('手机号已存在');
                $arrSet = [
                        'avatar' => strAddslashes(strstr($arrParam['avatar'], '/public/uploads/pic/')),
                        'realName' => strAddslashes($arrParam['realName']),
                        'phone' => $strPhone,
                        'updateTime' => request()->timestamp
                ];
                if (isset($arrParam['password']) && $arrParam['password']) {
                        if (mb_strlen($arrParam['password']) < 3 || mb_strlen($arrParam['password']) > 30) {
                                throw new \Exception('password is invalid length(min=3, max=30)');
                        }
                        $strSalt = mt_rand(1000, 9999);
                        $arrSet['password'] = md5(md5(strAddslashes($arrParam['password'])) . $strSalt);
                        $arrSet['salt'] = $strSalt;
                }
                $bool = SystemUser::renewal($arrWhere, $arrSet);
                if (!$bool) throw new \Exception('服务器处理数据失败');
                $arrSystemLogData = ['behavior' => '个人设置更新信息', 'operationBefore' => $arrOperationBefore, 'operationAfter' => $arrSet, 'whereData' => $arrWhere];
                setSystemLog($arrSystemLogData);
                return callbackParam(0, true, [], '操作成功');
        }
}